﻿using System.Linq;

using Concret;
using ORM;
using static Common;
using static DataLogic;

public class mList : HandlerBase
{
	/// <summary>
	/// 获取当前用户id
	/// </summary>
	/// <returns></returns>
	public dynamic currentUser()
	{
		var user = GetCurrentUser(DbOp);
		return new { id = user.Id.ToString(), name = user.Uname_Val };
	}

	/// <summary>
	/// 列出用户或所属的目录和文件
	/// </summary>
	/// <param name="owner">-1：列出我的所有图片，0：列出用户和所有目录，正数：列出目录下或用户下的图片</param>
	/// <returns></returns>
	public dynamic list(long owner)
	{
		var me = GetCurrentUser(DbOp);

		if (owner == 0)
			return new
			{
				me = new { id = me.Id.ToString(), name = me.Uname_Val, },
				dirs = DbOp.Dir.GetByFVs().Select(dir => new { id = dir.Id.ToString(), name = dir.Title_Val, count = dir.Dir__Photo().Count(), }),
			};
		else if (owner == -1)
			return me.User__Photo().OrderByDescending(p => p.Id).Select(photo => photoStruct(photo, true));

		return DbOp.Photo.GetByParameter((owner == me.Id ? Photo.FIELD_USER : Photo.FIELD_DIR, "=", owner)).OrderByDescending(p => p.Id).Select(photo => photoStruct(photo, photo.User_Val == me || me.IsAdmin()));
	}

	dynamic photoStruct(Photo photo, bool mine) => new
	{
		id = photo.Id.ToString(),
		title = photo.Title_Val,
		remark = photo.Remark_Val,
		path = photo.Path_Val,
		thumb = $"{photo.Path_Val}?thumb={ThumbQ.List}&update={photo.Updated_Val ?? 0}",
		mine = mine,
		user = photo.User_Val.Uname_Val,
		dir = photo.Dir_Val.Title_Val,
	};
}